package com.entrogy.timing;

import com.entrogy.bean.PubCountEntity;
import com.entrogy.dao.AttendanceMapper;
import com.entrogy.dao.MessageMapper;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.THDio;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Component
public class ChangePersonTimeThread extends Thread{

	private Logger logger = LoggerFactory.getLogger(ChangePersonTimeThread.class);

	@Autowired
	private MessageMapper messageMapper;//信息发送dao接口

	private String deviceId;
	private String personnelIds;
	private int type;
	private int cycleId;
	private String cycleName;
	private int passNumber;
	private long passStartTime;
	private long passEndTime;
	private String desc;
	private int leaveId;
	private HashMap<Integer, String> errMsg;
	//每个学校对应的设备管理系统后台的url
	private String pathUrl;
	private String key;
    public ChangePersonTimeThread(){}
	public ChangePersonTimeThread(String deviceId, String personnelIds, int type, int cycleId, String cycleName,
								  int passNumber, long passStartTime, long passEndTime, String desc, int leaveId, String pathUrl, String key) {
		this.deviceId = deviceId;
		this.personnelIds = personnelIds;
		this.type = type;
		this.cycleId = cycleId;
		this.cycleName = cycleName;
		// this.passNumber = passNumber * 20;
		this.passNumber = 100000;
		this.passStartTime = passStartTime;
		this.passEndTime = passEndTime;
		this.desc = desc;
		this.leaveId = leaveId;
		this.pathUrl = pathUrl;
		this.key = key;
		this.errMsg = new HashMap<>();
		this.errMsg.put(105, "设备不存在");
		this.errMsg.put(111, "设备不在线");
		this.errMsg.put(112, "链接设备超时");
		this.errMsg.put(113, "链接设备出错");
		this.errMsg.put(170, "设备不存在");
		this.errMsg.put(190, "人员不存在");
		this.errMsg.put(500, "服务器繁忙");
	}

	public void run() {
		THDio thd = new THDio();
		int threshTimes = 5;
		int sleepTime = 1000 * 60 * 5;
		JSONObject reqChangePersonnelPass = new JSONObject();
		reqChangePersonnelPass.put("device_ids", deviceId);
		reqChangePersonnelPass.put("personnel_ids", personnelIds);
		reqChangePersonnelPass.put("type", type);
		reqChangePersonnelPass.put("cycle_id", cycleId);
		reqChangePersonnelPass.put("pass_number", passNumber);
		reqChangePersonnelPass.put("pass_start_time", passStartTime);
		reqChangePersonnelPass.put("pass_end_time", passEndTime);
		String base = desc + " " + cycleName + " 设备" + deviceId + " ";
		int count = 0;
		do {
			count++;
			logger.info(base + "第" + count + "次" + "设置权限开始 " + reqChangePersonnelPass.toString());
			try {
				JSONObject resChangePersonnelPass = thd.THD_interface(pathUrl, "/competence/change_personnel_pass",
						reqChangePersonnelPass, false, key);
				int code = resChangePersonnelPass.getInt("code");
				// 打Log
				if (code == 0) {
					logger.info(base + "第" + count + "次" + "设置权限成功");
					if (leaveId > 0) {
						// 要把ispushtime置位1，表示以后不再推送
						try {
							if (TimingTaskService.doNotPushTime(leaveId)>0) {
								logger.info(leaveId + "的ispushtime置为1了！！！");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					break;
				} else {
					logger.info(base + "第" + count + "次" + "设置权限失败，原因：" + code + this.errMsg.get(code));
					// 重设5次还没成功就退出
					if (count > threshTimes) {
						logger.info(base + "第" + count + "次" + "设置权限超过" + threshTimes + "次了，退出");
						// 推送权限失败后需要推送消息给管理员
						String[] paramsWeiXin = { "",  "系统", "系统", new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()), "权限推送失败，请注意！失败状态码=>" + code, ""};
						PubCountEntity pubCountEntity = messageMapper.getPubCountOpenidByPhone("17628011691");
						// path参数为点击公众号消息后跳转的地址
						SendUtils.sendByWeixin(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId());
						break;
					}
				}
				Thread.sleep(sleepTime);
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("请注意推送学生通行权限出错啦啦");
				// 推送权限失败后需要推送消息给管理员
				String[] paramsWeiXin = { "",  "系统", "系统", new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()), "权限推送失败，请注意！实义德服务器挂了。。。", ""};
				PubCountEntity pubCountEntity = messageMapper.getPubCountOpenidByPhone("17628011691");
				// path参数为点击公众号消息后跳转的地址
				SendUtils.sendByWeixin(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId());
				break;
			}
		} while (true);
	}
}
